﻿using Component;
using Painter.Component;
using Painter.Model;
using PainterControl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace Painter
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        TabItem _mActiveDocument;
        TabItem mActiveDocument
        {
            get { return _mActiveDocument; }
            set
            {
                _mActiveDocument = value;
                position.SetBinding(ContentProperty, new System.Windows.Data.Binding("CurPos"){
                    Source = (mActiveDocument?.Content as LayerCanvas)?.scaleborder,
                    Mode = BindingMode.OneWay
                });
                size.SetBinding(ContentProperty, new System.Windows.Data.Binding("Sz_Width_Height"){
                    Source = ScaleData.Find_CreateScaleData((mActiveDocument?.Content as LayerCanvas)?.scaleborder),
                    Mode = BindingMode.OneWay
                });
                scale.SetBinding(RangeBase.ValueProperty, new System.Windows.Data.Binding("SliderValue"){
                    Source = (mActiveDocument?.Content as LayerCanvas)?.scaleborder,
                    Mode = BindingMode.OneWay
                });
                scale_text.SetBinding(ContentProperty, new System.Windows.Data.Binding("SliderTextValue"){
                    Source = (mActiveDocument?.Content as LayerCanvas)?.scaleborder,
                    Mode = BindingMode.OneWay
                });
            }
        }
        PluginManager mPluginManger = new PluginManager();
        public MainWindow()
        {
            InitializeComponent();
            mPluginManger.loadUIEvent += MPluginManger_loadUIEvent;
            mPluginManger.load();

            //拷贝数据
            mActiveDocument = pagesGroup.Items[0] as TabItem;
            ApplicationData.SetCanvas(((mActiveDocument.Content) as LayerCanvas).CanvasCollection.Cast<InkCanvas>().ToList());
            ApplicationData.SetTabControl(tabCtrl);

            pagesGroup.SelectionChanged += LayoutDocument_IsActiveChanged;
            PenSelect_Button_Click(this, null);
        }
        private void MPluginManger_loadUIEvent(IPainter ui)
        {
            if (ui is IPainterPannel)
            {
                //LayoutAnchorable anchor = new LayoutAnchorable();
                //anchor.Content = ui;
                //anchor.AutoHideMinWidth = anchor.FloatingWidth = 
                //    anchor.AutoHideWidth = (ui as IPainterPannel).GetWidth();
                //anchor.Title = (ui as IPainterPannel).GetTitle();
                //pluginPannel.Children.Add(anchor);
            }
            else if(ui is IPainterMenu)
            {
                (ui as IPainterMenu).AddMenu(plugin);
            }
        }
        private void EditColorButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ColorDialog colorDlg = new ColorDialog() { FullOpen =true };
                if (colorDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    int colorIndex = 20;
                    int.TryParse(colorPannel.Tag as string, out colorIndex);
                    if (colorIndex >= 30)
                    {
                        colorIndex = 29;
                        for (int i = 20; i < 29; i++)
                            (colorPannel.Children[i] as Border).Background = (colorPannel.Children[i + 1] as Border).Background;
                    }
                    System.Windows.Controls.Button border = (colorPannel.Children[colorIndex] as System.Windows.Controls.Button);
                    border.Foreground = border.Background = new SolidColorBrush(Color.FromArgb(
                        colorDlg.Color.A, colorDlg.Color.R, colorDlg.Color.G, colorDlg.Color.B));
                    colorPannel.Tag = (colorIndex + 1).ToString();
                }
            }
            catch { }
        }

        #region 页面
        private void NewPageMenuItem_Click(object sender, ExecutedRoutedEventArgs e)
        {
            TabItem item = new TabItem(){
                Header = "未命名",
                Style = Resources["tabPage"] as Style,
                Content = new LayerCanvas()
            };
            pagesGroup.Items.Add(item);
            pagesGroup.SelectedIndex = pagesGroup.Items.Count-1;
        }
        private void PagePath_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            pagesGroup.Items.Remove((e.Source as TextBlock).TemplatedParent);
        }
        private void PageClose_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            pagesGroup.Items.Remove(pagesGroup.SelectedItem);
        }
        #endregion

        private void OpenPageMenuItem_Click(object sender, ExecutedRoutedEventArgs e)
        {
            OpenFileDialog fdlg = new OpenFileDialog()
            {
                FilterIndex = 5,
                Filter = "单色位图(*.bmp)|*.bmp|16色位图(*.bmp)|*.bmp|256色位图(*.bmp)|*.bmp|24位位图(*.bmp)|*.bmp" +
                    "|JPEG(*.jpg)|*.jpg|GIF(*.gif)|*.gif|PNG(*.png)|*.png"
            };
            if (fdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.UriSource = new Uri(fdlg.FileName);
                bitmap.EndInit();

                DrawingVisual visual = new DrawingVisual();
                visual.FromImageSource(bitmap);
                (mActiveDocument?.Content as LayerCanvas).ActiveCanvas?.DrawPicture(visual);
            }
        }
        private void SavePageMenuItem_Click(object sender, ExecutedRoutedEventArgs e)
        {
            LayerCanvas activeCanvas = (mActiveDocument?.Content as LayerCanvas);
            if (string.IsNullOrEmpty(activeCanvas?.FullFileName))
            {
                SaveFileDialog fdlg = new SaveFileDialog()
                {
                    Title = "保存为",
                    FileName = "无标题",
                    FilterIndex = 7,
                    Filter = "单色位图(*.bmp)|*.bmp|16色位图(*.bmp)|*.bmp|256色位图(*.bmp)|*.bmp|24位位图(*.bmp)|*.bmp" +
                        "|JPEG(*.jpg)|*.jpg|GIF(*.gif)|*.gif|PNG(*.png)|*.png"
                };
                if (fdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    activeCanvas.FullFileName = fdlg.FileName;
                    if(mActiveDocument!=null) mActiveDocument.Header = System.IO.Path.GetFileName(fdlg.FileName);
                    activeCanvas?.SaveFile(activeCanvas.FullFileName);
                }
            }
        }
        private void SaveOtherMenuItem_Click(object sender, ExecutedRoutedEventArgs e)
        {
            LayerCanvas activeCanvas = (mActiveDocument?.Content as LayerCanvas);
            SaveFileDialog fdlg = new SaveFileDialog()
            {
                Title = "另存为",
                FileName = "无标题",
                FilterIndex = 7,
                Filter = "单色位图(*.bmp)|*.bmp|16色位图(*.bmp)|*.bmp|256色位图(*.bmp)|*.bmp|24位位图(*.bmp)|*.bmp" +
                "|JPEG(*.jpg)|*.jpg|GIF(*.gif)|*.gif|PNG(*.png)|*.png"
            };
            if (fdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                activeCanvas.FullFileName = fdlg.FileName;
                if (mActiveDocument != null) mActiveDocument.Header = System.IO.Path.GetFileName(fdlg.FileName);
                activeCanvas?.SaveFile(activeCanvas.FullFileName);
            }
        }
        #region 颜色
        private void ChangeColorButton_Click(object sender, RoutedEventArgs e)
        {
            SolidColorBrush brush = (sender as System.Windows.Controls.Button).Foreground as SolidColorBrush;
            if (brush != null)
            {
                if (mActiveDocument != null)
                    (mActiveDocument?.Content as LayerCanvas).CanvasCollection.ForEach(o => o.DefaultDrawingAttributes.Color = brush.Color);

                if (PaintSettings.inst().IsBackground)
                {
                    background_color.Background = brush;
                    PaintSettings.inst().BackgroundColor = brush.Color;
                }
                else
                {
                    foreground_color.Background = brush;
                    PaintSettings.inst().ForegroundColor = brush.Color;
                }
            }
        }
        private void ForeBackColor_Change_Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender == color1)
                PaintSettings.inst().IsBackground = false;

            if (sender == color2)
                PaintSettings.inst().IsBackground = true;
        }
        #endregion

        #region 缩放
        private void ZoomOut_Button_Click(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
                (mActiveDocument?.Content as LayerCanvas)?.Canvas_ZoomOut(1.2);
        }
        private void ZoomIn_Button_Click(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
                (mActiveDocument?.Content as LayerCanvas)?.Canvas_ZoomIn(1 / 1.2);
        }
        private void ZoomReset_Button_Click(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
                (mActiveDocument?.Content as LayerCanvas)?.Canvas_Reset();
        }
        private void FullScreen_Button_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Maximized;
        }
        #endregion

        private void Redo_Forward_Button_Click(object sender, ExecutedRoutedEventArgs e)
        {
            if (mActiveDocument != null)
                (mActiveDocument?.Content as LayerCanvas)?.mCmdStack.Redo();
        }
        private void Undo_Back_Button_Click(object sender, ExecutedRoutedEventArgs e)
        {
            if (mActiveDocument != null)
                (mActiveDocument?.Content as LayerCanvas)?.mCmdStack.Undo();
        }
        private void ExitMenuItem_Click(object sender, ExecutedRoutedEventArgs e)
        {
            Close();
        }
        private void ScaleCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
                (mActiveDocument.Content as LayerCanvas).scaleborder.BorderThickness = scaleCheck.IsChecked ?? false ? new Thickness(15,15,0,0):new Thickness();
        }
        private void GridCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
                (mActiveDocument.Content as LayerCanvas).grid.ShowGrid = showGridCheck.IsChecked ?? false;
        }
        private void OrginCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (toolBarHeight != null) toolBarHeight.Height = new GridLength(toolBarCheck.IsChecked??false?25:0);
        }
        private void Update_StackPanel_MouseLeftButtonUp(object sender, RoutedEventArgs e)
        {
            if (UpdateExe.Update())
                Process.Start(new ProcessStartInfo("Socks.PCClient.Updater.exe"));
        }
        
        #region 选择
        private void Copy_Button_Click(object sender, ExecutedRoutedEventArgs e)
        {
            try{
                if (mActiveDocument != null)
                    System.Windows.Clipboard.SetImage((mActiveDocument.Content as LayerCanvas).SaveBitmap());
            }
            catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); }
        }
        private void Cut_Button_Click(object sender, ExecutedRoutedEventArgs e)
        {
            try{
                if (mActiveDocument != null)
                    System.Windows.Clipboard.SetImage((mActiveDocument.Content as LayerCanvas).SaveBitmap());
            }
            catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); }
        }
        private void Paste_Button_Click(object sender, ExecutedRoutedEventArgs e)
        {
            try{
                if (System.Windows.Clipboard.ContainsImage())
                {
                    DrawingVisual visual = new DrawingVisual();
                    visual.FromImageSource(System.Windows.Clipboard.GetImage());
                    (mActiveDocument?.Content as LayerCanvas)?.ActiveCanvas.DrawFloatPicture(visual);
                }
            }
            catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); }
        }
        private void Cut_Expander_Collapsed(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
            {
                (mActiveDocument?.Content as LayerCanvas).CanvasCollection.ForEach(o =>
                {
                    o.UseCustomCursor = true;
                    o.EditingMode = InkCanvasEditingMode.Select;
                    o.Cursor = PaintSettings.inst().mCutCursor;
                });
                PaintSettings.inst().Cursor = PaintSettings.inst().mCutCursor;
                PaintSettings.inst().Mode = InkCanvasEditingMode.Select;
            }
        }
        private void LassoCut_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
            {
                rectSelect.IsChecked = false;
                lassoSelect.IsChecked = false;
                (sender as System.Windows.Controls.MenuItem).IsChecked = true;
                (mActiveDocument?.Content as LayerCanvas).CanvasCollection.ForEach(o =>
                {
                    if (sender == rectSelect)
                    {
                        o.mAdorner = Adorners.Rect;
                        o.EditingMode = InkCanvasEditingMode.Select;
                        o.Cursor = PaintSettings.inst().mCutCursor;
                    }
                    else if (sender == lassoSelect)
                    {
                        o.mAdorner = Adorners.Lasso;
                        o.EditingMode = InkCanvasEditingMode.Select;
                        o.Cursor = PaintSettings.inst().mCutCursor;
                    }
                });
                PaintSettings.inst().Cursor = PaintSettings.inst().mCutCursor;
                PaintSettings.inst().Mode = InkCanvasEditingMode.Select;
            }
        }
        #endregion

        private void Property_Button_Click(object sender, ExecutedRoutedEventArgs e)
        {
            PropertyWindow pWin = new PropertyWindow();
            pWin.Owner = this;
            pWin.ShowDialog();
        }
        private void LayoutDocument_IsActiveChanged(object sender, SelectionChangedEventArgs e)
        {
            mActiveDocument = (sender as System.Windows.Controls.TabControl)?.SelectedItem as TabItem;
            (layerPanel.Content as LayerControl).mCanvas = mActiveDocument?.Content as LayerCanvas;
            (layerPanel.Content as LayerControl).mCanvas?.CanvasCollection.ForEach(o => {
                if(o.InputBindings.Count==0)
                    o.InputBindings.AddRange(InputBindings);
            });
            if (mActiveDocument?.Content is LayerCanvas)
            {
                CommandStack stack = (mActiveDocument.Content as LayerCanvas).mCmdStack;
                if (stack != null)
                {
                    stack.EnableEvent -= LayoutDocument_Enable_UndoRedo;
                    stack.EnableEvent += LayoutDocument_Enable_UndoRedo;
                }
                ApplicationData.SetCanvas((mActiveDocument.Content as LayerCanvas).CanvasCollection.Cast<InkCanvas>().ToList());
            }
            PenSelect_Button_Click(this, null);
        }
        private void LayoutDocument_Enable_UndoRedo()
        {
            CommandStack stack = (mActiveDocument.Content as LayerCanvas)?.mCmdStack;
            undo.Source = new BitmapImage(new Uri(
                stack.Undo_Count() > 0 ? "pack://application:,,,/Resource/undo.png" : "pack://application:,,,/Resource/undo_n.png"));
            redo.Source = new BitmapImage(new Uri(
                stack.Redo_Count() > 0 ? "pack://application:,,,/Resource/redo.png" : "pack://application:,,,/Resource/redo_n.png"));
        }
        private void PenThick_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Shapes.Path path = (sender as System.Windows.Controls.MenuItem).Header as System.Windows.Shapes.Path;
            if(path !=null) (mActiveDocument?.Content as LayerCanvas).CanvasCollection.ForEach(o => {
                o.DefaultDrawingAttributes.Width = path.StrokeThickness;
                o.DefaultDrawingAttributes.Height = path.StrokeThickness;
            });
            PaintSettings.inst().PenSize = new Size(path.StrokeThickness, path.StrokeThickness);
        }        

        #region 工具
        private void PenSelect_Button_Click(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
            {
                (mActiveDocument?.Content as LayerCanvas).CanvasCollection.ForEach(o =>
                {
                    o.UseCustomCursor = true;
                    o.EditingMode = InkCanvasEditingMode.Ink;
                    o.Cursor = PaintSettings.inst().mPenCursor;
                });
                PaintSettings.inst().Cursor = PaintSettings.inst().mPenCursor;
            }
        }
        private void PutOil_Button_Click(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
            {
                (mActiveDocument?.Content as LayerCanvas).CanvasCollection.ForEach(o =>
                {
                    o.UseCustomCursor = true;
                    o.Cursor = PaintSettings.inst().mOilCursor;
                });
                PaintSettings.inst().Cursor = PaintSettings.inst().mOilCursor;
            }
        }
        private void Erase_Button_Click(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
            {
                (mActiveDocument?.Content as LayerCanvas).CanvasCollection.ForEach(o => {
                    o.UseCustomCursor = false;
                    o.EditingMode = InkCanvasEditingMode.EraseByPoint;
                    o.EraserShape = new RectangleStylusShape(o.DefaultDrawingAttributes.Width+4, o.DefaultDrawingAttributes.Width+4);
                });
                PaintSettings.inst().Cursor = null;
            }
        }
        private void TextInputButton_Click(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
            {
                (mActiveDocument?.Content as LayerCanvas).CanvasCollection.ForEach(o =>
                {
                    o.UseCustomCursor = true;
                    o.Cursor = System.Windows.Input.Cursors.IBeam;
                });
                PaintSettings.inst().Cursor = System.Windows.Input.Cursors.IBeam;
            }
        }
        private void GetColor_Button_Click(object sender, RoutedEventArgs e)
        {
            if (mActiveDocument != null)
            {
                (mActiveDocument?.Content as LayerCanvas).CanvasCollection.ForEach(o =>
                {
                    o.UseCustomCursor = true;
                    o.Cursor = PaintSettings.inst().mColorCursor;
                });
                PaintSettings.inst().Cursor = PaintSettings.inst().mColorCursor;
            }
        }
        #endregion
    }
}
